package com.example.server.service.implement;

import com.example.server.entity.User;
import com.example.server.mapper.UserMapper;
import com.example.server.service.UserService;
import com.example.server.utils.MD5Util;
import com.example.server.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByEmail(String email) {
        User u = userMapper.findByEmail(email);
        return u;
    }

    @Override
    public User findByUsername(String username) {
        User u = userMapper.findByUsername(username);
        return u;
    }

    @Override
    public User findById(Integer id) {
        User u = userMapper.findById(id);
        return u;
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }

    @Override
    public void register(String email, String password, String username) {
        //加密
        String md5String = MD5Util.md5(password);
        userMapper.insertUser(email, md5String, username);
    }

    @Override
    public void updateUsername(String username, Integer id) {
        userMapper.updateUsername(username,id);
    }

    @Override
    public void updatePassword(String password) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        userMapper.updatePwd(MD5Util.md5(password), userId);
    }

    @Override
    public void updateLastLogin(Integer id) {
        userMapper.updateLastLoginTime(id);
    }

    @Override
    public void updateAvatar(Integer id, String avatarUrl) {
        userMapper.updateAvatar(id, avatarUrl);
    }

    @Override
    public void changeRole(Integer id, String role) {
        userMapper.updateRole(id, role);
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }
}
